package com.zhj.bz.algorithm.sort.insert;

import com.zhj.tool.CallBack;
import com.zhj.tool.TimeTools;

import java.util.Arrays;

/**
 * @author zhj
 */
public class ShellSort {

    public static void main(String[] args) {
        int[] arr = {8, 9, 1, 7, 2, 4, 6, 0};
        sortPlus(arr);
        System.out.println(Arrays.toString(arr));
        int[] bigArr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            bigArr[i] = (int) (Math.random() * 80000);
        }
        System.out.println("希尔排序：");
        TimeTools.useTime(new CallBack(){
            //定义execute方法
            public void execute(){
                sort(bigArr);
            }
        });
        for (int i = 0; i < 80000; i++) {
            bigArr[i] = (int) (Math.random() * 80000);
        }
        System.out.println("优化希尔排序：");
        TimeTools.useTime(new CallBack(){
            //定义execute方法
            public void execute(){
                sortPlus(bigArr);
            }
        });
    }

    /**
     * 交换法
     * @param arr
     */
    public static void sort(int[] arr) {
        int temp = 0;
        // 进行分组
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            // 对组内数据进行冒泡
            for (int i = gap; i < arr.length; i++) {
                for (int j = i - gap; j >= 0; j -= gap) {
                    if (arr[j] > arr[j + gap]) {
                        temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                }
            }
        }
    }

    /**
     * 将交换法还为简单插入的移位法
     * @param arr
     */
    public static void sortPlus(int[] arr) {
        int temp = 0;
        // 进行分组
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            // 对组内数据进行直接插入
            int insertValue = 0;
            int insertIndex = 0;
            for (int i = gap; i < arr.length; i++) {
                insertValue = arr[i];
                insertIndex = i;
                // 保证插入位置不越界，找到位置循环暂停
                while (insertIndex - gap >= 0 && insertValue < arr[insertIndex - gap]) {
                    arr[insertIndex] = arr[insertIndex - gap];
                    insertIndex -= gap;
                }
                arr[insertIndex] = insertValue;
            }
        }
    }
}
